// Using subscribe-publish pattern, aka event bus or broker.
define([], function () {
	// Array of event subscribers.
	let subscribers = [];

	/**
	 * Subscribe to an event and execute the callback when triggered.
	 * @param {string} event
	 * @param {function} callback
	 */
	let subscribe = function (event, callback) {
		// A subscriber object.
		let subscriber = { event, callback };

		// Add the subscriber object to our local stack.
		subscribers.push(subscriber);

		// Update the subscribers array by removing this subscriber
		return function () {
			subscribers = subscribers.filter(function (e) {
				return e !== subscriber;
			});
		};
	};

	/**
	 * 
	 * @param {string} event
	 * @param {object} data
	 */
	let publish = function (event, data) {
		subscribers.forEach(function (s) {
			if (event === s.event) s.callback(data);
		});
	};

	return {
		subscribe,
		publish
	};
});